﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mindfor.Web
{
	/// <summary>
	/// Provides help function to work with directory services.
	/// </summary>
	public static class DirectoryServiceHelper
	{
		/// <summary>
		/// Converts domain string like "mydomain.com" to LDAP-string like "LDAP://DC=mydomain,DC=ru".
		/// </summary>
		/// <param name="domain">Domain string to convert.</param>
		public static string DomainToLdap(string domain)
		{
			if (String.IsNullOrEmpty(domain))
				return null;

			string[] s = domain.Split('.');
			StringBuilder sb = new StringBuilder("LDAP://");
			for (int i=0; i<s.Length; i++)
			{
				if (i != 0)
					sb.Append(",");
				sb.Append("DC=");
				sb.Append(s[i]);
			}
			return sb.ToString();
		}

		/// <summary>
		/// Converts  LDAP-string like "LDAP://DC=mydomain,DC=ru" to domain string like "mydomain.com".
		/// </summary>
		/// <param name="ldap">LDAP-string to convert.</param>
		public static string LdapToDomain(string ldap)
		{
			if (String.IsNullOrEmpty(ldap))
				return null;

			string protocol = "LDAP://";
			if (ldap.ToLower().StartsWith(protocol))
				ldap = ldap.Substring(protocol.Length);

			string[] s = ldap.Split(',');
			StringBuilder sb = new StringBuilder();
			for (int i=0; i<s.Length; i++)
			{
				if (s[i].ToLower().StartsWith("dc="))
				{
					if (sb.Length > 0)
						sb.Append(".");
					sb.Append(s[i].Substring("dc=".Length));
				}
			}
			return sb.ToString();
		}
	}
}
